/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.handler;

import com.huawei.api.bean.FileInfo;
import com.huawei.api.constants.Constant;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.utils.FileUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 文件处理
 *
 * @since 2023/10/28
 */
@Data
public class FileHandler implements Handler {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileHandler.class);

    private final FileInfo fileInfo;

    private final Set<String> filePaths;

    public FileHandler(FileInfo fileInfo) {
        this.fileInfo = fileInfo;
        this.filePaths = new HashSet<>();
    }

    @Override
    public void handle() throws BaseCustomerException {
        String source = fileInfo.getSource();
        // 获取文件列表,待检测文件夹和制定文件为空则返回
        if (!FileUtil.fileIsExists(source) && StringUtils.isBlank(fileInfo.getIncludeFiles())) {
            return;
        }
        // 如果路径是单个文件
        if (StringUtils.isNotBlank(source)) {
            File file = new File(source);
            if (file.isFile()) {
                filePaths.add(source);
            }
            //获取文件夹下所有的文件路径
            if (file.isDirectory()) {
                FileUtil.getFiles(file, filePaths);
            }
        }
        // 获取选取的文件
        String filePath = fileInfo.getIncludeFiles();
        if (StringUtils.isNotBlank(filePath)){
            List<String> list = Arrays.asList(filePath.split(Constant.COMMA));
            filePaths.addAll(list);
        }
        // 获取排除的文件
        String excludePath = fileInfo.getExcludeFiles();
        if (StringUtils.isNotBlank(excludePath)){
            List<String> list = Arrays.asList(filePath.split(Constant.COMMA));
            filePaths.remove(list);
        }
    }
}
